﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Query;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;

namespace Labthink.PCSoft.UniversalHost4.Instrument.Forms
{
    public partial class FrmSignal
    {
        public List<QuerySign> Querys { get; set; }
        private List<Esignal> _signals;

        public FrmSignal()
        {
            InitializeComponent();
        }

        private void BtnPrint_OnClick(object sender, RoutedEventArgs e)
        {
            var ids = new StringBuilder();
            foreach (var q in Querys)
            {
                ids.Append(q.TestId).Append(",");
            }

            var frm = new FrmSignalPrint { Signals = _signals, TestIds = ids.Remove(ids.Length - 1, 1).ToString() };
            frm.ShowDialog(this);
        }

        private void BtnAdd_OnClick(object sender, RoutedEventArgs e)
        {
            if (BtnAdd.Tag.ToString() == "ADD")
            {
                var cst = GridData.Items.Count;
                if (cst >= 3) return;
                if (cst == 0)
                {
                    Rb1.IsChecked = true;
                    Rb1.IsEnabled = true;
                }
                else if (cst == 1)
                {
                    Rb2.IsChecked = true;
                    Rb2.IsEnabled = true;
                }
                else
                {
                    Rb3.IsChecked = true;
                    Rb3.IsEnabled = true;
                }
                TxtRemark.IsEnabled = true;
                TxtRemark.Text = "";
                BtnAdd.Tag = "SAVE";
                //btnAdd.Text = "Save";
                BtnAdd.Content = LanguageManager.GetLanguageValue("Save");
            }
            else
            {
                _triggerButtonsStatus(false);
                var c = 0;
                foreach (var query in Querys)
                {
                    var signal = new Esignal
                    {
                        Date = DateTime.Now,
                        FilePath = query.FilePath,
                        Remark = TxtRemark.Text,
                        SignalType = GridData.Items.Count + 1,
                        TestId = query.TestId,
                        UserName = $"{Common.CurrentUser.LoginName}({Common.CurrentUser.UserName})"
                    };

                    var r = HistoryRepository.AddEsignals(signal);
                    var sn = _getSignName(signal.SignalType);
                    LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-AddSignInfo", sn, signal.TestId), "Data");

                    if (r >= 0) c++;
                }

                if (c > 0)
                {
                    MyMessageBox.Show(this, LanguageManager.GetLanguageValue("SignalSuccess" + (GridData.Items.Count + 1), c));
                    _loadSignals();
                }
                else
                {
                    MyMessageBox.Show(this, LanguageManager.GetLanguageValue("ActionFail"));
                }
                _triggerButtonsStatus(true);
                _initSignal();
            }
        }

        private static string _getSignName(int sign)
        {
            if (sign == 0) return LanguageManager.GetLanguageValue("UnSign");
            if (sign == 1) return LanguageManager.GetLanguageValue("Tested");
            if (sign == 2) return LanguageManager.GetLanguageValue("Checked");
            if (sign == 3) return LanguageManager.GetLanguageValue("Released");
            return LanguageManager.GetLanguageValue("UnSign");
        }

        private void BtnEdit_OnClick(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);
            var c = 0;
            foreach (var query in Querys)
            {
                var signal = new Esignal
                {
                    Date = DateTime.Now,
                    FilePath = query.FilePath,
                    Remark = TxtRemark.Text,
                    SignalType = TxtSignal.Text.ToInt(),
                    TestId = query.TestId
                };

                var r = HistoryRepository.UpdateEsignal(signal);
                var sn = _getSignName(signal.SignalType);
                LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-UpdateSignInfo", signal.TestId, sn), "Data");

                if (r >= 0) c++;
            }

            if (c > 0)
            {
                MyMessageBox.Show(this, LanguageManager.GetLanguageValue("SignalUpdateSuccess" + TxtSignal.Text.ToInt(), c));
                _loadSignals();
            }
            else
            {
                MyMessageBox.Show(this, LanguageManager.GetLanguageValue("ActionFail"));
            }
            _triggerButtonsStatus(true);
            _initSignal();
        }

        private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
        {
            if (
                MyMessageBox.Show(this, LanguageManager.GetLanguageValue("SureToDelete"), MyMessageBoxButton.OkCancel, MyMessageBoxImage.Warning, MyMessageBoxDefaultButton.Ok) == MyMessageBoxResult.Ok)
            {
                _triggerButtonsStatus(false);
                var c = 0;
                foreach (var query in Querys)
                {
                    var signal = new Esignal
                    {
                        Date = DateTime.Now,
                        FilePath = query.FilePath,
                        Remark = TxtRemark.Text,
                        SignalType = TxtSignal.Text.ToInt(),
                        TestId = query.TestId
                    };

                    var r = HistoryRepository.DeleteEsignals(signal);
                    var sn = _getSignName(signal.SignalType);
                    LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-DeleteSignInfo", signal.TestId, sn), "Data");

                    if (r >= 0) c++;
                }

                if (c > 0)
                {
                    MyMessageBox.Show(this, LanguageManager.GetLanguageValue("SignalDeleteSuccess" + TxtSignal.Text.ToInt(), c));
                    _loadSignals();
                    _initSignal();
                }
                else
                {
                    MyMessageBox.Show(this, LanguageManager.GetLanguageValue("ActionFail"));
                }
                _triggerButtonsStatus(true);
            }
        }

        private void FrmSignal_OnLoaded(object sender, RoutedEventArgs e)
        {
            _loadSignals();
        }

        private void GridData_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void _triggerButtonsStatus(bool status)
        {
            BtnDelete.IsEnabled = status;
            BtnAdd.IsEnabled = status;
            BtnEdit.IsEnabled = status;
            BtnPrint.IsEnabled = status;
            Loading.Visibility = status ? Visibility.Collapsed : Visibility.Visible;
        }

        private void _loadSignals()
        {
            _triggerButtonsStatus(false);
            _signals = HistoryRepository.GetEsignals(Querys.First().FilePath);
            GridData.ItemsSource = _signals;
            _triggerButtonsStatus(true);
            _initSignal();
        }

        private void _initSignal()
        {
            BtnAdd.Tag = "ADD";
            BtnAdd.Content = LanguageManager.GetLanguageValue("BtnAdd");
            Rb1.IsChecked = false;
            Rb2.IsChecked = false;
            Rb3.IsChecked = false;
            Rb1.IsEnabled = false;
            Rb2.IsEnabled = false;
            Rb3.IsEnabled = false;
            TxtRemark.IsEnabled = false;
            TxtRemark.Text = "";
            BtnEdit.IsEnabled = false;
            BtnDelete.IsEnabled = false;
            if (GridData.Items.Count >= 3)
            {
                BtnAdd.IsEnabled = false;
            }
            else if (GridData.Items.Count == 2)
            {
                BtnAdd.IsEnabled = HasPermission("Per_HistoryDataSignRelease");
            }
            else if (GridData.Items.Count == 1)
            {
                BtnAdd.IsEnabled = HasPermission("Per_HistoryDataSignCheck");
            }
            else
            {
                BtnAdd.IsEnabled = HasPermission("Per_HistoryDataSignTest");
            }
            if (GridData.Items.Count == 0)
            {
                BtnPrint.IsEnabled = false;
                BtnEdit.IsEnabled = false;
                BtnDelete.IsEnabled = false;
            }
            else
            {
                BtnPrint.IsEnabled = true;
            }
        }

        private static bool HasPermission(string permission)
        {
            return Common.Permissions.Any(p => p.Code == permission.Clear());
        }

        private void GridData_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var signal = GridData.SelectedItem as Esignal;
            if (signal == null) return;
            _initSignal();
            var idx = signal.SignalType;
            if (idx != GridData.Items.Count) return;
            var sameUser = signal.UserName == $"{Common.CurrentUser.LoginName}({Common.CurrentUser.UserName})";
            if (idx == 1)
            {
                Rb1.IsChecked = true;
                Rb1.IsEnabled = true;
                BtnDelete.IsEnabled = HasPermission("Per_HistoryDataSignTest") & sameUser;
                BtnEdit.IsEnabled = BtnDelete.IsEnabled;
            }
            else if (idx == 2)
            {
                Rb2.IsChecked = true;
                Rb2.IsEnabled = true;
                BtnDelete.IsEnabled = HasPermission("Per_HistoryDataSignCheck") & sameUser;
                BtnEdit.IsEnabled = BtnDelete.IsEnabled;
            }
            else
            {
                Rb3.IsChecked = true;
                Rb3.IsEnabled = true;
                BtnDelete.IsEnabled = HasPermission("Per_HistoryDataSignRelease") & sameUser;
                BtnEdit.IsEnabled = BtnDelete.IsEnabled;
            }

            TxtRemark.Text = signal.Remark;
            TxtRemark.IsEnabled = true;
            //btnAdd.Enabled = false;

            TxtSignal.Text = signal.SignalType + "";
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void TxtRemark_OnGotFocus(object sender, RoutedEventArgs e)
        {
            var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Keyboard.exe");
            if (!File.Exists(file)) return;
            POINT pt = new POINT();
            Win32Api.GetCursorPos(out pt);
            Process.Start(file, $"{pt.X} {pt.Y}");
        }

        private void TxtRemark_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (_isOpen()) return;
            if (sender is FrameworkElement fe)
            {
                fe.Focus();
            }
        }

        private bool _isOpen()
        {
            var name = "KeyboardWindow";
            var ptr = Win32Api.FindWindow(null, name);
            return ptr != IntPtr.Zero;
        }

        private void FrmSignal_OnMouseMove(object sender, MouseEventArgs e)
        {

        }
    }
}
